#include "pagenumberservice.h"
#include "pagedisplaystrategy.h"
#include "pagedisplaystrategyfactory.h"
#include "pagenumberconfigfacade.h"
#include "pagerendercontext.h"
#include "processingsettings.h"
#include "pageview.h"
#include <QDebug>
#include <QCryptographicHash>
#include <QTextStream>
#include <QFont>
#include <QColor>
PageNumberService& PageNumberService::instance()
{
    static PageNumberService instance;
    return instance;
}
void PageNumberService::initialize(PageNumberConfigFacade* configFacade,
                                  ProcessingSettings* processingSettings)
{
    m_configFacade = configFacade;
    m_processingSettings = processingSettings;
    // 初始化默认策略
    autoSelectStrategy(false, true);
}
// =================================================================
// 核心业务API实现
// =================================================================
PageNumberService::RenderResult PageNumberService::renderPageWithNumber(const RenderRequest& request)
{
    try {
        validateDependencies();
        if (request.sourceImage.isNull()) {
            return RenderResult::failure("源图像为空");
        }
        // 创建渲染上下文
        PageRenderContext context = createRenderContext(request);
        // 执行渲染
        return executeRender(request, context);
    } catch (const std::exception& e) {
        QString error = QString("渲染失败: %1").arg(e.what());
        qCritical() << "[PageNumberService] ❌" << error;
        return RenderResult::failure(error);
    }
}
QImage PageNumberService::renderForPageView(PageView* pageView, const QImage& sourceImage, int pageIndex)
{
    if (!pageView || sourceImage.isNull()) {
        return sourceImage;
    }
    // 注意：这个方法在测试环境中暂时简化实现
    // 在实际环境中会调用PageView的方法获取全局页码信息
    return sourceImage;
}
QImage PageNumberService::renderForExport(const QImage& sourceImage, int localPage, int globalPage, int totalPages)
{
    RenderRequest request;
    request.sourceImage = sourceImage;
    request.localPage = localPage;
    request.globalPage = globalPage;
    request.totalPages = totalPages;
    request.viewportSize = sourceImage.size();
    request.isExportMode = true;
    // 自动选择导出策略
    autoSelectStrategy(true, true);
    RenderResult result = renderPageWithNumber(request);
    return result.success ? result.renderedImage : sourceImage;
}
QString PageNumberService::previewPageNumber(int localPage, int globalPage, int totalPages, const QString& format)
{
    // 使用缓存提高性能
    QString cacheKey = getCacheKey(localPage, globalPage, totalPages, format);
    if (m_previewCache.contains(cacheKey)) {
        return m_previewCache[cacheKey];
    }
    QString actualFormat = format.isEmpty() ? (m_configFacade ? m_configFacade->getCurrentFormat() : "{page}") : format;
    // 只使用全局页码（忽略本地页码参数）
    QString result = PageNumberFormatter::generatePreview(actualFormat, globalPage, totalPages);
    // 缓存结果
    m_previewCache[cacheKey] = result;
    return result;
}
// =================================================================
// 策略管理API实现
// =================================================================
void PageNumberService::setDisplayStrategy(std::shared_ptr<PageDisplayStrategy> strategy)
{
    m_displayStrategy = strategy;
}
std::shared_ptr<PageDisplayStrategy> PageNumberService::getDisplayStrategy() const
{
    return m_displayStrategy;
}
void PageNumberService::autoSelectStrategy(bool isExportMode, bool needsPageNumber)
{
    PageDisplayStrategyFactory& factory = PageDisplayStrategyFactory::instance();
    auto strategyType = factory.selectStrategy(isExportMode, needsPageNumber);
    auto strategy = factory.createStrategy(strategyType);
    setDisplayStrategy(strategy);
}
// =================================================================
// 配置管理API实现
// =================================================================
void PageNumberService::updatePageNumberFormat(const QString& format)
{
    if (m_configFacade) {
        if (m_configFacade->isValidFormat(format)) {
            m_configFacade->setCurrentFormat(format);
            clearCache();  // 清除缓存
        } else {
        }
    }
}
void PageNumberService::updatePageNumberPosition(int position)
{
    if (m_configFacade) {
        m_configFacade->setCurrentPosition(position);
    }
}
void PageNumberService::updatePageNumberStyle(const QFont& font, const QColor& color)
{
    if (m_configFacade) {
        m_configFacade->setCurrentFont(font);
        m_configFacade->setCurrentColor(color);
    }
}
void PageNumberService::setPageNumberEnabled(bool enabled)
{
    if (m_configFacade) {
        m_configFacade->setPageNumberEnabled(enabled);
    }
}
void PageNumberService::applyConfigurationChanges()
{
    if (m_configFacade) {
        m_configFacade->applyAllChanges();
    }
    // 清除缓存以反映新配置
    clearCache();
}
// =================================================================
// 业务逻辑API实现
// =================================================================
bool PageNumberService::validateConfiguration(QString& errorMessage) const
{
    if (!m_configFacade) {
        errorMessage = "配置门面未初始化";
        return false;
    }
    if (!m_displayStrategy) {
        errorMessage = "显示策略未设置";
        return false;
    }
    QString currentFormat = m_configFacade->getCurrentFormat();
    if (!m_configFacade->isValidFormat(currentFormat)) {
        errorMessage = QString("无效的页码格式: %1").arg(currentFormat);
        return false;
    }
    return true;
}
int PageNumberService::calculateOptimalFontSize(const QSize& imageSize) const
{
    // 基于图像尺寸计算最佳字体大小
    int baseSize = qMax(8, qMin(imageSize.width(), imageSize.height()) / 50);
    // 限制在合理范围内
    return qBound(8, baseSize, 32);
}
bool PageNumberService::checkPageNumberOverlap(const QImage& image, const QSize& viewportSize) const
{
    // 简化实现：检查页码区域是否可能遮挡重要内容
    // 实际实现可能需要更复杂的图像分析
    Q_UNUSED(image)
    Q_UNUSED(viewportSize)
    return false;  // 假设不重叠
}
QString PageNumberService::generateConfigurationReport() const
{
    QString report;
    QTextStream stream(&report);
    stream << "=== 页码服务配置报告 ===" << Qt::endl;
    if (m_configFacade) {
        stream << "当前格式: " << m_configFacade->getCurrentFormat() << Qt::endl;
        stream << "页码启用: " << (m_configFacade->isPageNumberEnabled() ? "是" : "否") << Qt::endl;
        stream << "当前字体: " << m_configFacade->getCurrentFont().toString() << Qt::endl;
        stream << "当前颜色: " << m_configFacade->getCurrentColor().name() << Qt::endl;
    } else {
        stream << "配置门面: 未初始化" << Qt::endl;
    }
    if (m_displayStrategy) {
        stream << "显示策略: " << m_displayStrategy->getStrategyName() << Qt::endl;
    } else {
        stream << "显示策略: 未设置" << Qt::endl;
    }
    stream << "预览缓存条目: " << m_previewCache.size() << Qt::endl;
    return report;
}
// =================================================================
// 批处理API实现
// =================================================================
QList<PageNumberService::RenderResult> PageNumberService::batchRenderPages(const QList<RenderRequest>& requests)
{
    QList<RenderResult> results;
    results.reserve(requests.size());
    for (const auto& request : requests) {
        results.append(renderPageWithNumber(request));
    }
    return results;
}
QStringList PageNumberService::batchPreviewPageNumbers(const QList<QPair<int, int>>& pageNumbers, int totalPages)
{
    QStringList previews;
    previews.reserve(pageNumbers.size());
    for (const auto& pair : pageNumbers) {
        previews.append(previewPageNumber(pair.first, pair.second, totalPages));
    }
    return previews;
}
// =================================================================
// 内部辅助方法实现
// =================================================================
PageRenderContext PageNumberService::createRenderContext(const RenderRequest& request) const
{
    return PageRenderContext(
        request.globalPage - 1,  // 转换为0基索引
        request.totalPages,
        request.viewportSize,
        request.globalPage
    );
}
PageNumberService::RenderResult PageNumberService::executeRender(const RenderRequest& request, const PageRenderContext& context)
{
    if (!m_displayStrategy) {
        return RenderResult::failure("显示策略未设置");
    }
    try {
        // 使用策略渲染页面
        QImage renderedImage = m_displayStrategy->renderPage(request.sourceImage, context, m_processingSettings);
        // 获取实际显示的页码文本
        QString pageNumberText = context.formatPageNumber(m_configFacade ? m_configFacade->getCurrentFormat() : "{page}");
        return RenderResult(renderedImage, pageNumberText);
    } catch (const std::exception& e) {
        return RenderResult::failure(QString("策略渲染失败: %1").arg(e.what()));
    }
}
void PageNumberService::validateDependencies() const
{
    if (!m_configFacade) {
        throw std::runtime_error("配置门面未初始化");
    }
    if (!m_displayStrategy) {
        throw std::runtime_error("显示策略未设置");
    }
}
QString PageNumberService::generateErrorContext(const QString& operation) const
{
    return QString("[PageNumberService::%1] 在%2状态下").arg(operation).arg(
        m_configFacade ? "已配置" : "未配置"
    );
}
void PageNumberService::clearCache()
{
    m_previewCache.clear();
}
QString PageNumberService::getCacheKey(int localPage, int globalPage, int totalPages, const QString& format) const
{
    QString key = QString("%1_%2_%3_%4").arg(localPage).arg(globalPage).arg(totalPages).arg(format);
    return QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5).toHex();
}